package com.woniuxy.service.impl;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import com.woniuxy.entity.Comments;
import com.woniuxy.entity.CommentsVO;
import com.woniuxy.entity.User;
import com.woniuxy.mapper.CommentsMapper;
import com.woniuxy.mapper.UserMapper;
import com.woniuxy.service.CommentsService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service
public class CommentsServiceimpl implements CommentsService {
    @Resource
    private RedisTemplate<Object,Comments> redisTemplate;
    @Autowired
    private CommentsMapper commentsMapper;
    @Autowired
    private SnowflakeGenerator snowflakeIdWorder;

    @Autowired
    private UserMapper userMapper;

    @SneakyThrows
    @Transactional
    public void add(CommentsVO commentsVO) {
        Long next = snowflakeIdWorder.next();
        commentsVO.getComments().setId(next);
       int userId= commentsVO.getComments().getUserId();
       User user = userMapper.getUser(userId);
       commentsVO.getComments().setUserName(user.getUserName());
//        redisTemplate.opsForValue().set(commentsVO.getCinemaId()+"",commentsVO.getComments());
        redisTemplate.opsForHash().put(commentsVO.getCinemaId()+"",next.toString(),commentsVO.getComments());
        Comments comments =commentsVO.getComments();
        Long id = comments.getId();
        int UserId = comments.getUserId();
        String content =comments.getContent();
        commentsMapper.addComments(id,UserId,content);
        commentsMapper.add(commentsVO.getCinemaId(),next);
    }

    @SneakyThrows
    @Override
    public List<Comments> getByCinemaComments(Integer cinemaid) {
       List<Object> l = redisTemplate.opsForHash().values(cinemaid.toString());
       if(l.isEmpty()){
           List<Comments> ls= commentsMapper.getByCinemaComments(cinemaid);
           for (Comments comments:ls){
            User user =userMapper.getUser(comments.getUserId());
            comments.setUserName(user.getUserName());
            comments.setUserImg(user.getUserPicture());
           }
            return ls;
       }
        List<Comments> list = new ArrayList<>();
        for (Object o:l){
            Comments comments  = (Comments) o;
            list.add(comments);
        }
       return list;
    }
}
